package com.app.milkteaapp.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.app.milkteaapp.activity.DetailsActivity;
import com.app.milkteaapp.adapter.MilkTeaAdapter;
import com.app.milkteaapp.bean.AddCartGsonBean;
import com.app.milkteaapp.bean.AddOrlderGsonBean;
import com.app.milkteaapp.bean.LoginGsonBean;
import com.app.milkteaapp.bean.MilkTeaGsonBean;
import com.app.milkteaapp.R;
import com.app.milkteaapp.utils.GsonUtils;
import com.app.milkteaapp.utils.OkHttpUtils;
import com.app.milkteaapp.utils.MyTools;
import com.app.milkteaapp.utils.SpUtils;
import com.squareup.picasso.Picasso;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MilkteaFragment extends Fragment {

    private static final String TAG = "MilkteaFragment";
    private ListView listViewMilkTea;
    private ImageView topImg;
    private Context context = getContext();
    private LoginGsonBean.User user;

    public MilkteaFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_milktea, container, false);
        listViewMilkTea = view.findViewById(R.id.listview_milktea);
        user = SpUtils.getUserBean(context);
        topImg = view.findViewById(R.id.img_milktea_home);

        Picasso.get()
                .load(MyTools.URL+"/"+"home1.jpg")
                .into(topImg);
        getData();

        return view;
    }

    private void getData() {
        //get获取奶茶列表
        String url = MyTools.URL + "/milkTea/list";

        OkHttpUtils.MyCall(url).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "失败!请检查输入或网络!", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //gson解析
                String string = response.body().string();
                MilkTeaGsonBean milkTeaGsonBean = GsonUtils.fromJson(string, MilkTeaGsonBean.class);
                //当查询奶茶列表成功时,构建adapter并给listview使用
                if (milkTeaGsonBean.isSuccess()) {
                    //Log.d(TAG, "onResponse: milkteaList:"+milkTeaGsonBean.getData());
                    updateList(getContext(),milkTeaGsonBean.getData());
                }
            }
        });

    }

    /**
     * 更新奶茶list列表
     * @param context 上下文
     * @param list list
     */
    private void updateList(final Context context, final List<MilkTeaGsonBean.MilkTea> list) {
       getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                MilkTeaAdapter milkTeaAdapter = new MilkTeaAdapter(context, list,MilkteaFragment.this);
                listViewMilkTea.setAdapter(milkTeaAdapter);
                listViewMilkTea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        MilkTeaGsonBean.MilkTea milkTea = list.get(position);
                        int milkTeaId = milkTea.getId();

                        Intent intent = new Intent(getActivity(), DetailsActivity.class);
                        intent.putExtra("id", milkTeaId);
                        startActivity(intent);
                    }
                });
            }
        });
    }

    public void addOrderAndAddToCart(Integer teaid) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userid", user.getId());
            jsonObject.put("teaid", teaid);
            jsonObject.put("num", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call call = OkHttpUtils.MyCall(MyTools.URL + "/order/add", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                AddOrlderGsonBean addOrlderGsonBean = GsonUtils.fromJson(string, AddOrlderGsonBean.class);

                if (addOrlderGsonBean.isSuccess()) {
                    addToCart(addOrlderGsonBean.getData().getUserid(),addOrlderGsonBean.getData().getId());
                }
            }
        });
    }

    private void addToCart(Integer userid,Integer orderid) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userid", userid);
            jsonObject.put("orderid", orderid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call call = OkHttpUtils.MyCall(MyTools.URL + "/cart/add", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                AddCartGsonBean addCartGsonBean = GsonUtils.fromJson(string, AddCartGsonBean.class);

                if (addCartGsonBean.isSuccess()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "添加购物车成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }
}
